/*
 * @Description  : 租户列表页面
 * @Author       : Keyman
 * @Date         : 2025-11-15 17:05:19
 * @LastEditors  : Keyman
 * @LastEditTime : 2025-11-28 17:17:06
 */

import React, { useCallback, useEffect, useMemo, useState } from "react";
import type { DataType } from "./interface";
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Popconfirm,
  Row,
  Table,
  Tag,
  type TableProps,
} from "antd";
import { batchDeleteUser, deleteUser, getUserList } from "../../api/userList";
import type { PaginationConfig } from "antd/es/pagination";
import UserForm from "./userForm";
import { useDispatch } from "react-redux";
import { SetUserData } from "../../store/user/userSlice";

type searchType = {
  companyName?: string;
  contact?: string;
  phone?: string;
};

const MyUserForm = React.memo(UserForm);

function UsersList() {
  const [dataList, setDataList] = useState<DataType[]>([]);
  const dispatch = useDispatch();
  const [formData, setFormData] = useState<searchType>({
    companyName: "",
    contact: "",
    phone: "",
  });
  const [isVisible, setIsVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [page, setPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [title, setTitle] = useState<string>("");
  const [total, setTotal] = useState<number>(0);

  const disable = useMemo(() => {
    return selectedRowKeys.length > 0 ? false : true;
  }, [selectedRowKeys]);

  async function loadData() {
    const {
      data: { list, total },
    } = await getUserList({ ...formData, page, pageSize });
    setDataList(list);
    setTotal(total);
    setLoading(false);
  }

  useEffect(() => {
    setLoading(true);
    loadData();
  }, [page, pageSize]);

  const onChange: PaginationConfig["onChange"] = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const handleReset = () => {
    setSelectedRowKeys([]);
    setFormData({
      companyName: "",
      contact: "",
      phone: "",
    });
    setPage(1);
    setPageSize(10);
    loadData();
  };

  const handleSearch = () => {
    setLoading(true);
    loadData(); // 这里后端根据不同参数作为条件进行查询
  };

  const onSelectedChange = (selectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectedChange,
  };
  const confirm = async (id: string | number) => {
    console.log("删除");
    await deleteUser(id).then((res) => {
      console.log(res);
      const msg = res.message;
      message.success(msg);
      loadData();
    });
  };
  const batchDelete = async () => {
    console.log("删除");
    await batchDeleteUser(selectedRowKeys).then((res) => {
      console.log(res);
      const msg = res.message;
      message.success(msg);
      loadData();
    });
  };

  const edit = (record: DataType) => {
    setIsVisible(true);
    setTitle("编辑租户");
    dispatch(SetUserData(record));
  };

  const handleCancel = useCallback(() => {
    setIsVisible(false);
  }, []);

  const add = () => {
    setIsVisible(true);
    setTitle("新增租户");
    dispatch(SetUserData({}));
  };

  const columns: TableProps<DataType>["columns"] = [
    {
      title: "No.",
      key: "id",
      render: (_value, _record, index) => {
        return index + 1;
      },
    },
    {
      title: "客户名称",
      key: "name",
      dataIndex: "name",
    },
    {
      title: "经营状态",
      key: "status",
      dataIndex: "status",
      render: (value) => {
        if (value === "1") {
          return <Tag color="green">正常营业</Tag>;
        } else if (value === "2") {
          return <Tag color="red">停业</Tag>;
        } else if (value === "3") {
          return <Tag color="orange">暂停营业</Tag>;
        }
        return <Tag color="black">未知</Tag>;
      },
    },
    {
      title: "联系电话",
      key: "tel",
      dataIndex: "tel",
    },
    {
      title: "所属行业",
      key: "bussiness",
      dataIndex: "bussiness",
    },
    {
      title: "邮箱",
      key: "email",
      dataIndex: "email",
    },
    {
      title: "统一信用代码",
      key: "creditCode",
      dataIndex: "creditCode",
    },
    {
      title: "工商注册号",
      key: "industryNum",
      dataIndex: "industryNum",
    },
    {
      title: "组织结构代码",
      key: "organizationCode",
      dataIndex: "organizationCode",
    },
    {
      title: "法人名",
      key: "legalPerson",
      dataIndex: "legalPerson",
    },
    {
      title: "操作",
      key: "operate",
      render(_value, record) {
        return (
          <>
            <Button onClick={() => edit(record)} size="small" type="primary">
              编辑
            </Button>
            <Popconfirm
              cancelText="否"
              description="确定删除吗？"
              onConfirm={() => confirm(record.id)}
              okText="是"
              title="删除确认"
            >
              <Button className="ml" danger size="small" type="primary">
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  return (
    <>
      <div className="usersList">
        <MyUserForm onCancel={handleCancel} open={isVisible} title={title} />
        <Card className="search">
          <Row gutter={16}>
            <Col span={7}>
              <p>企业名称：</p>
              <Input
                name="companyName"
                value={formData.companyName}
                onChange={handleChange}
              ></Input>
            </Col>
            <Col span={7}>
              <p>联系人：</p>
              <Input
                name="contact"
                value={formData.contact}
                onChange={handleChange}
              ></Input>
            </Col>
            <Col span={7}>
              <p>联系电话：</p>
              <Input
                name="phone"
                value={formData.phone}
                onChange={handleChange}
              ></Input>
            </Col>
            <Col span={3}>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
              <Button className="ml" onClick={handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Card>
        <Card className="mt tr">
          <Button onClick={add} type="primary">
            新增企业
          </Button>
          <Button
            className="ml"
            disabled={disable}
            onClick={batchDelete}
            type="primary"
          >
            批量删除
          </Button>
        </Card>
        <Card className="mt">
          <Table<DataType>
            columns={columns}
            dataSource={dataList}
            loading={loading}
            pagination={{
              onChange,
              current: page,
              pageSize,
              position: ["bottomRight"],
              showTotal: (total) => `共 ${total} 条数据`,
              showQuickJumper: true,
              total,
            }}
            rowKey={(record) => record.id}
            rowSelection={rowSelection}
          ></Table>
        </Card>
      </div>
    </>
  );
}

export default UsersList;
